<?php
/**
 * 管理员登录
 * @author zlj <389843954@qq.com>
 */

namespace app\manage\controller;
use app\common\model\User;
use app\common\model\Login as LoginModel;
use app\common\model\Verify;
use think\Session;
use think\Db;
class Login extends Common
{
	/**
	 * 登录界面
	 * @return [type] [description]
	 */
	public function index(){
		return view('',['title'=>'管理人员登录']);
	}

	/**
	 * 登录操作
	 */
	public function Login(){
		if(request()->isAjax()){
			$tel = input('post.tel',false);
			$code = input('post.code',false);

			if(!$tel || !$code){
				show(false,'请填写手机号与验证码');
			}

			if(!checkTel($tel)){
				show(false,'手机号格式不正确');
			}

			$userModel = new User();
			$loginModel = new LoginModel();
			$verifyModel = new Verify();

			$info = $userModel->getOne('uid,name',['phone'=>$tel]);
			if(!$info){
				show(false,'此用户不存在');
			}
			
			$login = $loginModel->checkLogin($info['uid']);
			if(!$login){
				$loginModel->addLogin($info['uid']);
				show(false,'错误登录次数过多,请'.config('CHECK_OUT_TIME').'分钟后再登录');
			}
			//验证验证码
			$res = $verifyModel->Ver($tel,$code);
			if($res['code']){
				$loginModel->delLogin($info['uid']);

				$user['id'] = $info['uid'];
				$user['name'] = $info['name'];
				$user['type'] = $info['type'];

				session('user',$user);
				show(true,'登录成功');
			}else{
				//错误登录,进行记录
				$loginModel->addLogin($info['uid']);

				show(false,$res['msg']);
			}
		}
	}

	/**
	 * 登录发短信
	 * @return [type] [description]
	 */
	public function sendCode(){
		if(request()->isAjax()){
			$tel = input('post.tel',false);

			if(!checkTel($tel)){
				show(false,'手机号格式不正确');
			}

			$userModel = new User();
			$verifyModel = new Verify();

			$info = $userModel->getOne('uid,name',['phone'=>$tel]);
			if(!$info){
				show(false,'此用户不存在');
			}
			
			$res = $verifyModel->sendTelCode($tel,false);

			if($res['code']){
				show(true,'发送成功');
			}else{
				show(false,'发送失败,请重试!');
			}
		}
	}

    /**
     * 退出
     * @return [type] [description]
     */
    public function outlogin(){
        session::clear();

        $this->redirect('Login/index');
    }
}